package cn.bon.websocket.handler;

import cn.bon.common.adapter.JsonSerializerAdapter;
import cn.bon.common.utils.JwtUtils;
import cn.bon.websocket.config.JsonUtilConfig;
import cn.bon.websocket.pool.UserPool;
import cn.bon.websocket.pool.WaitingAuthenticationUserPool;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

/**
 * @author: dronff
 * @description:
 * @CreateTime: 2023/12/11 8:39
 **/
@Component
@ConditionalOnBean(JsonSerializerAdapter.class)
@Data
public class WebsocketServerInitializerHandler extends ChannelInitializer<NioSocketChannel> {
    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private UserPool userPool;

    @Resource
    private JsonSerializerAdapter jsonSerializerAdapter;
    private final WaitingAuthenticationUserPool waitingAuthenticationUserPool = new WaitingAuthenticationUserPool();
    @Override
    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
        ChannelPipeline pipeline = nioSocketChannel.pipeline();
        pipeline.addLast(new HttpServerCodec())
                .addLast(new ChunkedWriteHandler())
                .addLast(new HttpObjectAggregator(8192))
                .addLast(new WebSocketServerProtocolHandler("/ws","WebSocket",true,65536*10))
                .addLast(new WebsocketCoreHandler(userPool,jsonSerializerAdapter,jwtUtils));

    }
}
